<template>
    <div class="risk-item-control-set">
        <div class="risk-control-button">
            <el-card>
                <el-select
                    placeholder="同步类型"
                    size="mini"
                    @change="handleParam(value, 'importType')"
                    class="risk-el-select"
                    style="width:150px;margin-right:10px"
                    v-model="name.syncParam.importType"
                >
                    <el-option value="0" key="0" label=" 0 单个同步"></el-option>
                    <el-option value="1" key="1" label="1 增量同步"></el-option>
                    <el-option value="2" key="2" label="2 全量同步"></el-option>
                </el-select>
                <el-input
                    placeholder="维度编号"
                    @change="handleParam(name.syncParam.dynamicCode, 'dynamicCode')"
                    style="width:100px;margin-right:10px"
                    :style="{ display: name.syncParam.importType === '0' ? '' : 'none' }"
                    size="mini"
                    v-model="name.syncParam.dynamicCode"
                ></el-input>
                <el-select
                    placeholder="来源类型"
                    @change="handleParam(name.syncParam.sourceType, 'sourceType')"
                    class="risk-el-select"
                    style="width:150px;margin-right:10px"
                    size="mini"
                    v-model="name.syncParam.sourceType"
                >
                    <el-option value="25" key="25" label="全部"></el-option>
                    <el-option value="2" key="2" label="恒生-主动库"></el-option>
                    <el-option value="5" key="5" label="恒生-被动库"></el-option>
                </el-select>
                <el-switch
                    active-text="执行ETL"
                    inactive-text="跳过ETL"
                    @change="handleParam(name.syncParam.dynamicETL, 'dynamicETL')"
                    style="margin-right:10px"
                    size="mini"
                    v-model="name.syncParam.dynamicETL"
                />
                <el-button icon="el-icon-link" v-authCode.show="B_0087" type="primary" :loading="syncLoading" @click="handleClickSync" size="mini">
                    同步
                </el-button>
                <div style="float:right">
                    <el-input placeholder="维度编号，支持‘,’分割" style="width:250px;margin-right:10px" size="mini" v-model="name.initDynamicCodes" />
                    <el-button
                        v-authCode.show="B_0087"
                        icon="el-icon-refresh"
                        type="primary"
                        size="mini"
                        :loading="syncLoading"
                        @click="handleInitDynamicClick"
                    >
                        初始化SQL
                    </el-button>
                </div>
            </el-card>
        </div>
        <el-tabs v-model="activeKey">
            <el-tab-pane :label="'同步结果'" :name="'current'" :key="'current'">
                <CurrentSyncContent
                    :type="'current'"
                    :outerAmount="outerAmount"
                    :tranParams="{ ...name.syncParam }"
                    :ref="'current'"
                ></CurrentSyncContent>
            </el-tab-pane>
            <el-tab-pane :label="'历史同步结果'" :name="'history'" :key="'history'">
                <HistorySyncContent :type="'history'" :tranParams="name.syncParam" :ref="'history'"></HistorySyncContent>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>
<script lang="ts">
import RiskPagination from '@/common/components/risk-pagination.vue';
import { getCurrentPageData } from '@/utils/tools';
import { Component, Vue } from 'vue-property-decorator';
import HistorySyncContent from '../setting/components/item-sync/history-sync-content.vue';
import CurrentSyncContent from '../setting/components/item-sync/current-sync-content.vue';

export interface pages {
    currentPage?: number;
    pageSize?: number;
    total?: number;
}
@Component({
    name: 'DynamicSync',
    components: {
        RiskPagination,
        CurrentSyncContent,
        HistorySyncContent,
    },
})
export default class DynamincSync extends Vue {
    private activeKey: string = 'current';
    panes: any[] = [
        { label: '同步结果', name: 'current' },
        { label: '历史同步结果', name: 'history' },
    ];
    private syncResult: any = {
        totalAmount: '',
        successAmount: '',
        successEntry: '',
        errorAmount: '',
        errorDynamic: '',
        errorMsg: '',
        etlResult: '',
    };
    private syncLoading: boolean = false;
    private hsControlDefines: any = [];
    private name: any = {
        syncParam: {
            dynamicCode: '',
            importType: '1',
            dynamicETL: false,
            sourceType: '2',
        },
        errorMessage: {},
        initEntryCodes: '',
    };

    outerAmount: any = {
        totalAmount: 0,
        successAmount: 0,
        errorAmount: 0,
    };
    mounted() {
        this.handleData();
    }

    private handleParam(value: string, filed: string): void {}

    // 初始化SQL
    private handleInitDynamicClick(): void {
        if (this.name.initDynamicCodes) {
            this.syncLoading = true;
            this.$axios.post('/dynamic/dynamic/sql', this.name.initDynamicCodes.split(',')).then(
                (res: any) => {
                    console.log(res);

                    if (res && res.length > 0) {
                        this.yh_message_success('执行成功，但以下动态维度无法解析' + res.join(','));
                        // this.$message({
                        //     type: 'success',
                        //     message: '执行成功，但以下动态维度无法解析' + res.join(','),
                        // });
                    } else if (!res) {
                        this.yh_message_warn('维度编号不存在,无法完成初始化');
                        this.syncLoading = false;
                        return;
                    } else {
                        this.yh_message_success('初始化执行成功');
                    }
                    this.syncLoading = false;
                },
                () => {
                    this.syncLoading = false;
                }
            );
        } else {
            this.$confirm('确定要初始化所有动态维度的SQL吗？', '', {
                confirmButtonText: 'confirm',
                cancelButtonText: 'cancel',
                type: 'warning',
            })
                .then(() => {
                    this.$axios.get('/dynamic/all/dynamic/sql').then(
                        (res: any) => {
                            if (res && res.length > 0) {
                                this.yh_message_success('执行成功，但以下动态维度无法解析' + res.join(','));
                                // this.$message({
                                //     type: 'info',
                                //     message: '执行成功，但以下动态维度无法解析' + res.join(','),
                                // });
                            } else {
                                this.yh_message_success('初始化执行成功');
                            }
                            this.syncLoading = false;
                        },
                        () => {
                            this.syncLoading = false;
                        }
                    );
                })
                .catch(() => {});
        }
    }

    // 同步
    private handleClickSync(): void {
        let nSyncParam = this.name.syncParam;
        if (nSyncParam.importType === '0') {
            if (!nSyncParam.dynamicCode) {
                this.yh_message_error('动态维度编号不可为空');
                return;
            }
        }
        let syncParam = JSON.parse(JSON.stringify(nSyncParam));
        if (nSyncParam.importType === '0') {
            syncParam.importType = '0';
        } else if (nSyncParam.importType === '1') {
            syncParam.dynamicCode = '';
            syncParam.importType = '1';
        } else if (nSyncParam.importType === '2') {
            syncParam.dynamicCode = '';
            syncParam.importType = '2';
        }
        this.syncLoading = true;
        // 清空数据
        this.$axios.post('/dataEngine/syncDynamic', syncParam).then(
            (res: any) => {
                // if (!res.successDynamic && !res.errorDynamic) {
                //     this.yh_message_error(res.errorMsg);
                //     this.syncLoading = false;
                //     return;
                // }
                this.outerAmount.totalAmount = res.totalAmount || 0;
                this.outerAmount.successAmount = res.successAmount || 0;
                this.outerAmount.errorAmount = res.errorAmount || 0;
                // if (!res.batchId && res.batchId !== 0) {
                this.beforeDestory();
                this.handleData(res.batchId);
                // }
                this.syncLoading = false;
            },
            () => {
                this.syncLoading = false;
            }
        );
    }
    async handleData(batchId?: any) {
        // 将batchId传递给子组件 todo
        (this.$refs['current'] as any).handleClickSync('0', false, '0', 'userAction', batchId);
        (this.$refs['current'] as any).handleClickSync('1', false, '0', 'userAction', batchId);
        this.setIntervalCurrent = setInterval(() => {
            (this.$refs['current'] as any).handleClickSync('1', true, '0', 'autoRefresh');
        }, 60 * 1000);
        (this.$refs['history'] as any).handleClickSync('0');
    }

    setIntervalCurrent = null;

    beforeDestory() {
        console.log('beforeDestory-------------');
        if (this.setIntervalCurrent) {
            clearInterval(this.setIntervalCurrent);
            this.setIntervalCurrent = null;
        }
    }
}
</script>
<style lang="scss" scoped>
.risk-item-control-set {
    min-width: 1200px;
}
/deep/ .el-tabs .el-tabs__nav .el-tabs__item {
    border: 1px solid #cacaca !important;
    margin: 5px;
    height: 100%;
}
/deep/ .el-tab-pane {
    color: #000;
}
</style>
